package cn.easybuy.web.pre;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.easybuy.dao.order.CartService;
import cn.easybuy.dao.order.CartServiceImpl;
import cn.easybuy.entity.Product;
import cn.easybuy.entity.User;
import cn.easybuy.entity.UserAddress;
import cn.easybuy.service.proudct.ProductCategoryService;
import cn.easybuy.service.proudct.ProductCategoryServiceImpl;
import cn.easybuy.service.proudct.ProductService;
import cn.easybuy.service.proudct.ProductServiceImpl;
import cn.easybuy.utils.Constants;
import cn.easybuy.utils.EmptyUtils;
import cn.easybuy.utils.ProductCategoryVo;
import cn.easybuy.utils.ReturnResult;
import cn.easybuy.utils.ShoppingCart;
import cn.easybuy.web.AbstractServlet;


@WebServlet(urlPatterns= {"/CartServlet"},name="CartServlet")
public class CartServlet extends AbstractServlet {
	
	private ProductService productService;
	private ProductCategoryService productCategoryService;
	private CartService cartService;
	
	public void init() throws ServletException {
		productService = new ProductServiceImpl();
		productCategoryService = new ProductCategoryServiceImpl();
		cartService = new CartServiceImpl();
	}

	@Override
	public Class getServletClass() {
		
		return CartServlet.class;
	}
	
	/**
	 * 	添加购物车
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public ReturnResult add(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ReturnResult result = new ReturnResult();
		String id = request.getParameter("entityId");
		String quantityStr = request.getParameter("quantity");
		Integer quantity = 1;
		
		if (EmptyUtils.isNotEmpty(quantityStr)) {
			quantity = Integer.parseInt(quantityStr);
		}
		
		//查询出商品
		Product product = productService.findById(id);
		if (product.getStock() < quantity) {
			return result.returnFail("商品数量不足");
		}
		//获取购物车
		ShoppingCart cart = getCartFromSession(request);
		
		//往购物车添加商品
		result = cart.addItem(product, quantity);
		
		//如果放置成功
		if (result.getStatus() == Constants.ReturnResult.SUCCESS) {
			cart.setSum(EmptyUtils.isEmpty(cart.getSum())?0.0:cart.getSum()+(product.getPrice()*quantity*1.0));
		}
		
		return result;
	} 
	
	/**
	 * 	从session中获取购物信息
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private ShoppingCart getCartFromSession(HttpServletRequest request) throws Exception {
		
		HttpSession session = request.getSession();
		ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
		
		if (EmptyUtils.isEmpty(cart)) {
			cart = new ShoppingCart();
			session.setAttribute("cart", cart);
		}
		
		return cart;
	}

	public String refreshCart(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		return "/common/pre/searchBar";
	}
	
	
	public String toSettlement(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<ProductCategoryVo> pcList = productCategoryService.queryAllProductCategory();
		request.setAttribute("pcList", pcList);
		return "/pre/settlement/toSettlement";
	}
	
	
	/**
	 * 	跳转到购物车维护页面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String toSettlment1(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		return "/pre/settlement/settlement1";
	}
	
	
	public ReturnResult modifyCart(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		ReturnResult result = new ReturnResult();
		HttpSession session = request.getSession();
		String id = request.getParameter("entityId");
		String quantityStr = request.getParameter("quantity");
		
		if (EmptyUtils.isEmpty(id) || EmptyUtils.isEmpty(quantityStr)) {
			return result.returnFail("参数不能为空");
		}
		Integer quantity = Integer.parseInt(quantityStr);
		ShoppingCart cart = getCartFromSession(request);
		Product product = productService.findById(id);
		
		if (quantity > product.getStock()) {
			return result.returnFail("商品数量不足");
		}
		
		//修改购物车
		cart = cartService.modifyShoppingCart(id, quantity, cart);
		session.setAttribute("cart", cart);
		return result.returnSuccess();
		
	}
	
	
	  /**
     * 跳转到购物车页面
     *
     * @param request
     * @param response
     * @return
     */
    public String settlement1(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	ShoppingCart cart = getCartFromSession(request);
    	cart = cartService.calculate(cart);
    	request.getSession().setAttribute("cart",cart);
    	return "/pre/settlement/settlement1";
    }
	
	
	public String settlement2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		User user = getUserFromSession(request);
		List<UserAddress> userAddresses;
		
		return "/pre/settlement/settlement2";
		
	}
	
	   /**
     * @param request
     * @return
     */
    private User getUserFromSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        return user;
    }
	
}
